package constant_tools;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

public class FileTools {


    //获取文件32位MD5值
    public static String getMD5(MultipartFile multipartFile) throws NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        try (DigestInputStream dis = new DigestInputStream(multipartFile.getInputStream(), md)) {
            // 读取文件内容，同时更新MD5
            while(dis.read() != -1) ;
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] digest = md.digest();
        // 将字节数组转换为十六进制字符串
        StringBuilder result = new StringBuilder();
        for (byte b : digest) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }

    public static void filesTozip(List<File> fileList, File zip){
        FileInputStream fileInputStream = null;
        FileOutputStream fileOutputStream = null;
        ZipOutputStream zipOutputStream = null;
        BufferedInputStream bufferInputStream = null;
        try {
            fileOutputStream = new FileOutputStream(zip);
            zipOutputStream = new ZipOutputStream(new BufferedOutputStream(fileOutputStream));
            // 创建读写缓冲区
            byte[] bufs = new byte[1024 * 10];

            for (File file : fileList) {
                // 创建ZIP实体，并添加进压缩包
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zipOutputStream.putNextEntry(zipEntry);

                // 读取待压缩的文件并写进压缩包里
                fileInputStream = new FileInputStream(file);
                bufferInputStream = new BufferedInputStream(fileInputStream, 1024 * 10);
                int read = 0;
                while ((read = bufferInputStream.read(bufs, 0, 1024 * 10)) != -1) {
                    zipOutputStream.write(bufs, 0, read);
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferInputStream != null) {
                    bufferInputStream.close();
                }
                if (zipOutputStream != null) {
                    zipOutputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }



}
